<template>
  <div>
    <QuillEditor
      ref="myQuillEditor"
      theme="snow"
      v-model:content="content"
      :options="data.editorOption"
      contentType="html"
      @update:content="setValue()"
    />
    <!-- 使用自定义图片上传 -->
    <!-- <input type="file" hidden accept=".jpg,.png" ref="fileBtn" @input="handleUpload" /> -->
    <el-upload
      :action="uploadUrl"
      :before-upload="handleBeforeUpload"
      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      name="file"
      :show-file-list="false"
      :headers="headers"
      class="editor-img-uploader"
    >
      <i ref="fileBtn" class="editor-img-uploader" />
    </el-upload>
  </div>
</template>

<script lang="ts" setup>
import { ElMessage } from "element-plus"

import { QuillEditor } from "@vueup/vue-quill"
import "@vueup/vue-quill/dist/vue-quill.snow.css"
import { reactive, onMounted, ref, toRaw, watch } from "vue"
import { getToken } from "@/utils/cache/cookies"
const uploadUrl = ref(import.meta.env.VITE_BASE_API + "//h5Package/upload") // 上传的图片服务器地址
const headers = ref({
  token: getToken()
})

const props = defineProps(["value"])
const emit = defineEmits(["updateValue"])
const content = ref("")
const myQuillEditor = ref()
watch(
  () => props.value,
  (val) => {
    // effectUpdate(val)
    content.value = val
    // setValue()
  },
  {
    deep: true
  }
)
const fileBtn = ref()
const data = reactive({
  content: "",
  editorOption: {
    modules: {
      toolbar: [
        ["bold", "italic", "underline", "strike"],
        [{ size: ["small", false, "large", "huge"] }],
        [{ font: [] }],
        [{ align: [] }],
        [{ list: "ordered" }, { list: "bullet" }],
        [{ indent: "-1" }, { indent: "+1" }],
        [{ header: 1 }, { header: 2 }],
        ["image"],
        [{ direction: "rtl" }],
        [{ color: [] }, { background: [] }]
      ]
    },
    placeholder: "请输入内容..."
  }
})
const imgHandler = (state: any) => {
  if (state) {
    fileBtn.value.click()
  }
}
const setValue = () => {
  const text = toRaw(myQuillEditor.value).getHTML()
  emit("updateValue", text)
}

// 上传前校检格式和大小
const handleBeforeUpload = (file: any) => {
  const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"]
  const isJPG = type.includes(file.type)
  //检验文件格式
  if (!isJPG) {
    ElMessage.error(`图片格式错误!`)
    return false
  }
  // 校检文件大小
  const size = ref(25)
  const fileSizeFlag = file.size / 1024 / 1024 < size.value
  if (!fileSizeFlag) {
    ElMessage.error(`请上传不大于${size.value}M的图片!`)
  }
  return true
}

// 上传成功处理
function handleUploadSuccess(res: any) {
  // 如果上传成功
  if (res.code == 200) {
    const quill = toRaw(myQuillEditor.value).getQuill()
    const length = quill.getSelection().index
    // 插入图片，res为服务器返回的图片链接地址
    quill.insertEmbed(length, "image", res.data)
    // 调整光标到最后
    quill.setSelection(length + 1)
  } else {
    ElMessage.error("图片插入失败")
  }
}

// 上传失败处理
function handleUploadError() {
  ElMessage.error("图片插入失败")
}

// const handleUpload = (e: any) => {
//   const files = Array.prototype.slice.call(e.target.files)
//   // console.log(files, "files")
//   if (!files) {
//     return
//   }
//   const formdata = new FormData()
//   formdata.append("file", files[0])
//   uploadComboImageList(formdata).then((res: any) => {
//     if (res.code == 200) {
//       const quill = toRaw(myQuillEditor.value).getQuill()
//       const length = quill.getSelection().index
//       // 插入图片，res为服务器返回的图片链接地址
//       quill.insertEmbed(length, "image", res.data)
//       // 调整光标到最后
//       quill.setSelection(length + 1)
//     }
//   })
// }
const effectUpdate = (val: any) => {
  const quill = toRaw(myQuillEditor.value).getQuill()
  if (myQuillEditor.value) {
    quill.getModule("toolbar").addHandler("image", imgHandler)
  }
  toRaw(myQuillEditor.value).setHTML(val)
}
onMounted(() => {
  effectUpdate(props.value)
})
</script>
<style scoped lang="scss">
:deep(.ql-editor) {
  min-height: 180px;
}
:deep(.ql-formats) {
  height: 21px;
  line-height: 21px;
}
</style>
